iT邦幫忙

0

bind, call, apply

  • 分享至 

  • xImage
  •  

在未經過綁定的this會指向Windows

Bind

使用Bind會return 一個function


let Dennis = {
    name: "Dennis",
    age: 22
}
function hello() {
    console.log(this) //指向Window
    console.log(this.age)
}

hello() //undefined

https://ithelp.ithome.com.tw/upload/images/20210521/20130419Qo7Dszql1s.png


所以這邊使用bind method綁定在指定的物件身上


let Dennis = {
    name: "Dennis",
    age: 22
}
function hello() {
    console.log(this) //指向Dennis
    console.log(this.age) //22
}

const Hello = hello.bind(Dennis)
Hello()

https://ithelp.ithome.com.tw/upload/images/20210521/20130419pJPOs52ZVh.png


Call

使用call 會直接執行,所以不需要變數接住function再執行

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello() {
    console.log(this) //指向Dennis
    console.log(this.age) //22
}

hello.call(Dennis)

並且 call可以傳入參數

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello(parameter) {
    console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}

hello.call(Dennis,) //My name is Dennis phonenumber is undefined

加入參數

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello(parameter) {
    console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}

hello.call(Dennis, "0900123123") //My name is Dennis phonenumber is 0900123123

Apply

apply跟call幾乎一樣,不同於傳入參數型態,若是array使用apply,string等等使用call


let c = ["000000"]

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello(parameter) {
    console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}

hello.apply(Dennis, c) //My name is Dennis phonenumber is 000000

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言